package org.csu.onlineedubackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.csu.onlineedubackend.entity.ForumLike;
import org.csu.onlineedubackend.entity.ForumPost;
import org.csu.onlineedubackend.entity.ForumNotification;
import org.csu.onlineedubackend.mapper.ForumLikeMapper;
import org.csu.onlineedubackend.mapper.ForumPostMapper;
import org.csu.onlineedubackend.mapper.ForumNotificationMapper;
import org.csu.onlineedubackend.service.ForumLikeService;
import org.csu.onlineedubackend.service.ForumUserStatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ForumLikeServiceImpl implements ForumLikeService {
    @Autowired
    private ForumLikeMapper forumLikeMapper;
    
    @Autowired
    private ForumPostMapper forumPostMapper;
    
    @Autowired
    private ForumUserStatsService forumUserStatsService;

    @Autowired
    private ForumNotificationMapper forumNotificationMapper;

    @Override
    public boolean like(Integer userId, Integer postId, Integer commentId) {
        // 檢查是否已經點贊
        if (isLiked(userId, postId, commentId)) {
            return false;
        }

        ForumLike like = new ForumLike();
        like.setUserId(userId);
        like.setPostId(postId);
        like.setCommentId(commentId);
        
        boolean result = forumLikeMapper.insert(like) > 0;

        // 添加通知
        if (postId != null) {
            ForumPost post = forumPostMapper.selectById(postId);
            if (post != null && !post.getUserId().equals(userId)) {
                ForumNotification notification = new ForumNotification();
                notification.setUserId(post.getUserId()); // 接收者
                notification.setSenderId(userId);
                notification.setType(1); // 點贊
                notification.setTargetType(1); // 帖子
                notification.setTargetId(postId);
                notification.setContent("您的帖子獲得了點贊");
                notification.setIsRead(0);
                forumNotificationMapper.insert(notification);
            }
        } else if (commentId != null) {
            // 點贊評論，目前簡單處理，可自行查評論作者
        }

        return result;
    }

    @Override
    public boolean unlike(Integer userId, Integer postId, Integer commentId) {
        LambdaQueryWrapper<ForumLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumLike::getUserId, userId)
               .eq(postId != null, ForumLike::getPostId, postId)
               .eq(commentId != null, ForumLike::getCommentId, commentId);
        
        return forumLikeMapper.delete(wrapper) > 0;
    }

    @Override
    public boolean isLiked(Integer userId, Integer postId, Integer commentId) {
        LambdaQueryWrapper<ForumLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumLike::getUserId, userId)
               .eq(postId != null, ForumLike::getPostId, postId)
               .eq(commentId != null, ForumLike::getCommentId, commentId);
        
        return forumLikeMapper.selectCount(wrapper) > 0;
    }

    @Override
    public int getPostLikeCount(Integer postId) {
        LambdaQueryWrapper<ForumLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumLike::getPostId, postId);
        return forumLikeMapper.selectCount(wrapper).intValue();
    }

    @Override
    public int getCommentLikeCount(Integer commentId) {
        LambdaQueryWrapper<ForumLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumLike::getCommentId, commentId);
        return forumLikeMapper.selectCount(wrapper).intValue();
    }

    @Override
    public int getUserReceivedLikeCount(Integer userId) {
        // 1. 先查询用户的所有帖子
        LambdaQueryWrapper<ForumPost> postWrapper = new LambdaQueryWrapper<>();
        postWrapper.eq(ForumPost::getUserId, userId);
        List<ForumPost> userPosts = forumPostMapper.selectList(postWrapper);
        
        // 2. 统计这些帖子获得的总点赞数
        int totalLikes = 0;
        for (ForumPost post : userPosts) {
            LambdaQueryWrapper<ForumLike> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(ForumLike::getPostId, post.getId());
            totalLikes += forumLikeMapper.selectCount(likeWrapper).intValue();
        }
        
        return totalLikes;
    }

    @Override
    public int getUserGivenLikeCount(Integer userId) {
        LambdaQueryWrapper<ForumLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumLike::getUserId, userId);
        return forumLikeMapper.selectCount(wrapper).intValue();
    }

    @Override
    public java.util.List<org.csu.onlineedubackend.dto.ForumLikeDTO> getLikesByUser(Integer userId) {
        LambdaQueryWrapper<ForumLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumLike::getUserId, userId)
               .isNull(ForumLike::getCommentId) // 只查帖子點贊
               .orderByDesc(ForumLike::getCreatedAt);

        java.util.List<ForumLike> likes = forumLikeMapper.selectList(wrapper);

        java.util.List<org.csu.onlineedubackend.dto.ForumLikeDTO> dtoList = new java.util.ArrayList<>();
        for (ForumLike like : likes) {
            // 檢查帖子狀態，只保留 active 的帖子
            org.csu.onlineedubackend.entity.ForumPost post = forumPostMapper.selectById(like.getPostId());
            if (post == null || post.getStatus() == null || !"active".equalsIgnoreCase(post.getStatus())) {
                continue; // 跳過已刪除或狀態非 active 的帖子
            }

            org.csu.onlineedubackend.dto.ForumLikeDTO dto = new org.csu.onlineedubackend.dto.ForumLikeDTO();
            org.springframework.beans.BeanUtils.copyProperties(like, dto);
            dtoList.add(dto);
        }
        return dtoList;
    }
} 